package com.warrantyhotel.android.service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.preference.PreferenceManager;
import android.util.Log;

import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.util.HttpConnector;
import com.warrantyhotel.android.util.JSONParser;

/**
 * DataUpdateService - manages connection to server, retrieves data from it,
 * parses the response and updates database with new values in background
 * thread.
 */
public class UpdateWarrantyService extends IntentService {

	private static final String TAG = UpdateWarrantyService.class.getSimpleName();

	public static final String EXTRA_STATUS_RECEIVER = "extra_receiver";
	public static final String EXTRA_REQUEST_CODE = "request_code";
	public static final String ERROR_MESSAGE = "err_msg";
	public static final String RECORDS = "records";

	public static final int STATUS_RUNNING = 1;
	public static final int STATUS_ERROR = 2;
	public static final int STATUS_FINISHED = 3;

	private JSONParser jsonParser;
	private ContentResolver resolver;
	private static SharedPreferences prefs;

	private int queryCode;

	private final HttpConnector connector;

	public UpdateWarrantyService() {
		super(TAG);
		connector = HttpConnector.getInstance();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		resolver = getBaseContext().getContentResolver();
		jsonParser = new JSONParser(resolver, this);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
	}

	/**
	 * This method manages sends request to a server, parses response from it
	 * and updates database with new values.
	 */
	@Override
	protected void onHandleIntent(final Intent intent) {

		final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
		if (null != receiver)
			receiver.send(STATUS_RUNNING, null);

		queryCode = intent.getIntExtra(EXTRA_REQUEST_CODE, -1);
		final Bundle resultData = new Bundle();
		String url;
		String response = "";

		final String accountId = prefs.getString(Keys._accountId, null);
		final String tokenId = prefs.getString(Keys._tokenId, null);

		// final int records;
		try {
			switch (queryCode) {
			case QueriesCodes.WARRANTY_BY_ACCOUNT_ID:
				// warranty list parse
				receiver.send(STATUS_RUNNING, null);
				final int stepIteration = 20;
				int initialPosition = 0;
				int maxCount = stepIteration + 1;
				ArrayList<String> remains = new ArrayList<String>();
				do {
					url = "Warranty/ByAccountID(" + accountId + "," + tokenId + "," + initialPosition + "," + stepIteration + ",null)";
					response = connector.sendGETRequest(url);
					if (null != response)
						Log.e("responce", response);
					JSONObject obj = new JSONObject(response);
					maxCount = obj.getInt("Total");
					remains = jsonParser.parseWarrantyJSON(new JSONObject(response), remains);
					initialPosition += stepIteration;
					resultData.putInt(Keys.actionIdentificator, QueriesCodes.WARRANTY_BY_ACCOUNT_ID);
					receiver.send(STATUS_FINISHED, resultData);

				} while (initialPosition <= maxCount);
				jsonParser.removeWarrantyRemains(remains);

				resultData.putInt(Keys.actionIdentificator, QueriesCodes.WARRANTY_BY_ACCOUNT_ID);
				receiver.send(STATUS_FINISHED, resultData);

				break;

			case QueriesCodes.ACCOUNT_UPLOAD_BY_ACCOUNT_ID:
				url = "AccountUpload/ByAccountID(" + accountId + "," + tokenId + ")";
				response = connector.sendGETRequest(url);
				jsonParser.parseUploadWaJSON(new JSONObject(response));
				// Log.i("AccountUpload/ByAccountID", response);
				resultData.putInt(Keys.actionIdentificator, QueriesCodes.ACCOUNT_UPLOAD_BY_ACCOUNT_ID);
				receiver.send(STATUS_FINISHED, resultData);
				break;

			default:
				break;
			}

		} catch (URISyntaxException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "Unable to connect server...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (ClientProtocolException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (IOException ex) {
			Log.e(TAG, ex.getMessage(), ex);
			Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		} catch (Exception ex) {
			Log.e(TAG, ex.getMessage(), ex);
			final Bundle errInfo = new Bundle();
			errInfo.putString(ERROR_MESSAGE, "No internet connection...");
			if (null != receiver)
				receiver.send(STATUS_ERROR, errInfo);
		}
	}
}
